package repository

import (
	"context"
	"database/sql"

	"gitee.com/hp-huiw/family-expense-api/internal/db"
	dbmodel "gitee.com/hp-huiw/family-expense-api/internal/db/model"
	jet "github.com/go-jet/jet/v2/mysql"
)

type Region struct {
	ID    string `db:"id"`
	Name  string `db:"name"`
	Title string `db:"title"`
}

type RegionRepository interface {
	Exists(ctx context.Context) (bool, error)
	Query(ctx context.Context) ([]Region, error)
	BatchInsert(ctx context.Context, models []dbmodel.Region) error
}

func NewRegionRepository(db *sql.DB) RegionRepository {
	return &regionRepository{db: db}
}

// Exists checks if any existing region data.
func (r *regionRepository) Exists(ctx context.Context) (bool, error) {
	return db.Exists(ctx, r.db, tbRegion, nil)
}

// Query queries all regions.
func (r *regionRepository) Query(ctx context.Context) ([]Region, error) {
	var query []struct {
		ID    string `db:"id"`
		Name  string `db:"name"`
		Title string `db:"title"`
	}

	stmt := jet.
		SELECT(
			tbRegion.ID.AS("id"),
			tbRegion.Name.AS("name"),
			tbRegion.Title.AS("title"),
		).
		FROM(
			tbRegion,
		).
		ORDER_BY(
			tbRegion.Name.ASC(),
		)

	if err := stmt.QueryContext(ctx, r.db, &query); err != nil {
		return nil, err
	}

	result := make([]Region, 0, len(query))

	for _, item := range query {
		result = append(result, item)
	}

	return result, nil
}

// BatchInsert inserts multiple regions.
func (r *regionRepository) BatchInsert(ctx context.Context, models []dbmodel.Region) error {
	stmt := tbRegion.
		INSERT().
		MODELS(models)

	_, err := stmt.ExecContext(ctx, r.db)

	return err
}

type regionRepository struct {
	db *sql.DB
}
